package com.wtwd.wtwddevice.deviceserver.handler;


import com.wtwd.device.constant.DeviceLoginEnum;
import com.wtwd.device.constant.MsgTypeEnum;
import com.wtwd.device.protocol.WTProtocol;
import com.wtwd.wtwddevice.deviceserver.model.DeviceSession;
import com.wtwd.wtwddevice.deviceserver.netty.LocalSessions;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MsgHandler implements IMsgHandler {

    @Override
    public void processMessage(WTProtocol wtProtocol, Channel channel) {
        try {
            ProcessMessageHandler handler = MsgHandlerFactory.createProcessMessageHandler(wtProtocol.getCmdName());
            WTProtocol result = handler.processMsg(wtProtocol, channel);
            if (result == null) return;
            ChannelFuture channelFuture = channel.writeAndFlush(result);//某部分消息服务器收到直接进行应答
        } catch (Exception e) {
            log.error("协议处理异常{}-{}", wtProtocol.toString(), e.getMessage());
        }
    }

    @Override
    public void sendMessage(WTProtocol wtProtocol) {
        String cmdName = wtProtocol.getCmdName();
        DeviceSession session;
        if (MsgTypeEnum.DEVICE_LOGIN.getCmdName().equals(cmdName)) {//
            if (wtProtocol.getBody().equals(DeviceLoginEnum.DEVICE_SUCCESS.getBody())){
                session = LocalSessions.deviceLoginSession(wtProtocol.getImei());
            }else {
                session = LocalSessions.getDeviceSession(wtProtocol.getImei());
            }
        } else {
            session = LocalSessions.getDeviceSession(wtProtocol.getImei());
        }
        ChannelFuture channelFuture = session.getChannel().writeAndFlush(wtProtocol);
        channelFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (channelFuture.isSuccess()) {
                    log.info("直接下发消息,成功-{}", wtProtocol.toString());
                } else {
                    log.info("直接下发消息,失败-{},{}", wtProtocol.toString());
                }
            }
        });

    }


}
